<template>
  <div class="activity-container">
    <!-- 顶部导航栏 -->
    <div class="header-section">
      <div class="title-container">
        <div class="breadcrumb-title">
          <span class="main-title">活动批次管理</span>
        </div>
      </div>
      <div class="header-actions">
        <el-button
            type="primary"
            class="back-btn"
            @click="goBack"
        >
          <el-icon><ArrowLeft /></el-icon>返回队伍管理
        </el-button>
        <el-button
            type="primary"
            @click="showCreateDialog"
            class="create-btn"
        >
          <el-icon><Plus /></el-icon>创建批次
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <div class="search-bar">
        <el-input
            v-model="searchQuery"
            placeholder="请输入批次名称搜索"
            class="search-input"
            clearable
            @clear="handleReset"
            @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button @click="handleSearch" class="search-btn">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button @click="handleReset" class="reset-btn">
          <el-icon><Refresh /></el-icon>重置
        </el-button>
      </div>
    </el-card>

    <!-- 批次表格 -->
    <el-card shadow="never" class="table-card">
      <el-table
          :data="pagedBatchList"
          style="width: 100%"
          border
          class="batch-table"
          :header-cell-style="headerCellStyle"
      >
        <el-table-column prop="id" label="序号" width="80" align="center"></el-table-column>
        <el-table-column prop="name" label="批次名称" align="center" width="180"></el-table-column>
        <el-table-column prop="year" label="批次学年" align="center" width="150"></el-table-column>
        <el-table-column prop="startTime" label="开始时间" align="center" width="180"></el-table-column>
        <el-table-column prop="endTime" label="结束时间" align="center" width="180"></el-table-column>
        <el-table-column prop="status" label="批次状态" align="center" width="120">
          <template #default="{row}">
            <el-tag
                :type="getStatusType(row.status)"
                effect="light"
                class="status-tag"
            >
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template #default="{row}">
            <el-button
                v-if="row.status === '运行中'"
                type="primary"
                size="small"
                @click="showEditDialog(row)"
                class="edit-btn"
            >
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button
                v-else
                type="info"
                size="small"
                @click="showDetailDialog(row)"
                class="detail-btn"
            >
              <el-icon><View /></el-icon>详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="filteredBatchList.length"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建批次对话框 -->
    <el-dialog
        v-model="createDialogVisible"
        title="创建母校行活动批次"
        width="500px"
        class="create-dialog"
    >
      <el-form :model="createForm" label-width="100px" class="dialog-form">
        <el-form-item label="批次名称：" required>
          <el-input
              v-model="createForm.name"
              placeholder="请输入批次名称"
              clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="关联年份：" required>
          <el-select
              v-model="createForm.year"
              placeholder="请选择关联年份"
              style="width: 100%"
              clearable
          >
            <el-option
                v-for="year in yearOptions"
                :key="year"
                :label="year"
                :value="year"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间：" required>
          <el-date-picker
              v-model="createForm.startTime"
              type="datetime"
              placeholder="请选择开始时间"
              style="width: 100%"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间：" required>
          <el-date-picker
              v-model="createForm.endTime"
              type="datetime"
              placeholder="请选择结束时间"
              style="width: 100%"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="handleCreateSubmit" class="submit-btn">提交</el-button>
      </template>
    </el-dialog>

    <!-- 编辑批次对话框 -->
    <el-dialog
        v-model="editDialogVisible"
        title="编辑母校行活动批次"
        width="500px"
        class="edit-dialog"
    >
      <el-form :model="editForm" label-width="100px" class="dialog-form">
        <el-form-item label="批次名称：" required>
          <el-input
              v-model="editForm.name"
              placeholder="请输入批次名称"
              clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="关联年份：" required>
          <el-select
              v-model="editForm.year"
              placeholder="请选择关联年份"
              style="width: 100%"
              clearable
          >
            <el-option
                v-for="year in yearOptions"
                :key="year"
                :label="year"
                :value="year"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间：" required>
          <el-date-picker
              v-model="editForm.startTime"
              type="datetime"
              placeholder="请选择开始时间"
              style="width: 100%"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间：" required>
          <el-date-picker
              v-model="editForm.endTime"
              type="datetime"
              placeholder="请选择结束时间"
              style="width: 100%"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="延长结束时间：">
          <el-date-picker
              v-model="editForm.extendEndTime"
              type="datetime"
              placeholder="请选择延长结束时间"
              style="width: 100%"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit" class="submit-btn">提交</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="活动详情"
        width="800px"
        class="detail-dialog"
        align-center
        :top="'5vh'"
    >
      <div class="detail-content">
        <div class="detail-header">
          <h3>{{ currentDetail.name }}</h3>
          <el-tag
              :type="getStatusType(currentDetail.status)"
              effect="light"
              class="status-tag"
          >
            {{ currentDetail.status }}
          </el-tag>
        </div>

        <el-descriptions :column="2" border class="detail-info">
          <el-descriptions-item label="批次学年">{{ currentDetail.year }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ currentDetail.startTime }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ currentDetail.endTime }}</el-descriptions-item>
        </el-descriptions>

        <div class="photo-section">
          <div class="section-title">
            <el-icon><Picture /></el-icon>
            <span>活动照片</span>
          </div>
          <div v-if="currentDetail.photos && currentDetail.photos.length > 0" class="photo-grid">
            <div v-for="(photo, index) in currentDetail.photos" :key="index" class="photo-item">
              <div class="photo-wrapper">
                <el-image
                    :src="photo.url"
                    :preview-src-list="currentDetail.photos.map(p => p.url)"
                    :initial-index="index"
                    fit="cover"
                    class="photo-image"
                ></el-image>
                <div class="photo-overlay">
                  <el-button
                      type="primary"
                      size="small"
                      circle
                      :icon="ZoomIn"
                      @click.stop="previewPhoto(index)"
                      class="preview-btn"
                  />
                </div>
              </div>
              <p class="photo-desc">{{ photo.description || '活动照片' }}</p>
            </div>
          </div>
          <div v-else class="no-photos">
            <el-empty description="暂无活动照片" :image-size="100"></el-empty>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false" class="close-btn">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft,
  Search,
  Plus,
  Refresh,
  Edit,
  View,
  Picture,
  ZoomIn
} from '@element-plus/icons-vue'

export default {
  name: 'Activity',
  components: {
    Refresh,
    Plus,
    ArrowLeft,
    Search
  },
  setup() {
    const router = useRouter()

    // 批次列表数据
    const batchList = ref([
      {
        id: 1,
        name: '母校行夏季批次',
        year: '2022-2023年',
        startTime: '2023-06-01 00:00:00',
        endTime: '2023-08-31 23:59:59',
        status: '运行中',
        photos: [
          { url: 'https://jsj.scujj.edu.cn/sys/FCKFileUpload/9335611F158384098324876D5B56AA47.png', description: '合照' },
          { url: 'https://jsj.scujj.edu.cn/sys/FCKFileUpload/1BB69A0AB2C6A0B320E625755095CB61.png', description: '活动照片' }
        ]
      },
      {
        id: 2,
        name: '母校行国庆批次',
        year: '2022-2023年',
        startTime: '2023-10-01 00:00:00',
        endTime: '2023-10-07 23:59:59',
        status: '已结束',
        photos: [
          { url: 'https://jsj.scujj.edu.cn/sys/FCKFileUpload/1E3D424B1FAADB743A869ED8D2D343B3.png', description: '现场照片' }
        ]
      },
      {
        id: 3,
        name: '母校行五一活动批次',
        year: '2022-2023年',
        startTime: '2023-05-01 00:00:00',
        endTime: '2023-05-03 23:59:59',
        status: '已结束',
        photos: []
      },
      {
        id: 4,
        name: '春季活动批次',
        year: '2023-2024年',
        startTime: '2024-03-01 00:00:00',
        endTime: '2024-05-31 23:59:59',
        status: '运行中',
        photos: [
          { url: 'https://jsj.scujj.edu.cn/sys/FCKFileUpload/IMG_0311.JPG', description: '春季活动' }
        ]
      },
      {
        id: 5,
        name: '秋季活动批次',
        year: '2023-2024年',
        startTime: '2023-09-01 00:00:00',
        endTime: '2023-11-30 23:59:59',
        status: '已结束'
      }
    ])

    // 详情对话框相关
    const detailDialogVisible = ref(false)
    const currentDetail = ref({
      name: '',
      year: '',
      startTime: '',
      endTime: '',
      status: '',
      photos: []
    })

    // 搜索相关
    const searchQuery = ref('')
    const filteredBatchList = computed(() => {
      if (!searchQuery.value) return batchList.value
      const query = searchQuery.value.toLowerCase()
      return batchList.value.filter(item =>
          item.name.toLowerCase().includes(query) ||
          item.year.toLowerCase().includes(query))
    })

    // 分页相关
    const currentPage = ref(1)
    const pageSize = ref(10)
    const pagedBatchList = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return filteredBatchList.value.slice(start, end)
    })

    // 年份选项
    const yearOptions = ref([
      '2020-2021年',
      '2021-2022年',
      '2022-2023年',
      '2023-2024年',
      '2024-2025年'
    ])

    // 创建批次相关
    const createDialogVisible = ref(false)
    const createForm = reactive({
      name: '',
      year: '',
      startTime: '',
      endTime: ''
    })

    // 编辑批次相关
    const editDialogVisible = ref(false)
    const editForm = reactive({
      id: '',
      name: '',
      year: '',
      startTime: '',
      endTime: '',
      extendEndTime: ''
    })

    // 返回队伍管理
    const goBack = () => {
      router.push('/manage/Teammanage')
    }

    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
    }

    // 重置搜索
    const handleReset = () => {
      searchQuery.value = ''
      currentPage.value = 1
    }

    // 分页大小变化
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
    }

    // 当前页变化
    const handleCurrentChange = (val) => {
      currentPage.value = val
    }

    // 显示详情对话框
    const showDetailDialog = (row) => {
      currentDetail.value = { ...row }
      // 确保photos数组存在
      if (!currentDetail.value.photos) {
        currentDetail.value.photos = []
      }
      detailDialogVisible.value = true
    }

    // 预览照片
    const previewPhoto = (index) => {
      const imageList = currentDetail.value.photos.map(p => p.url)
      const image = imageList[index]
      // 这里使用Element Plus的图片预览功能
      // 实际项目中可能需要根据具体实现调整
      const img = new Image()
      img.src = image
      const viewer = new Viewer(img, {
        hidden: function() {
          viewer.destroy()
        }
      })
      viewer.show()
    }

    // 显示创建批次对话框
    const showCreateDialog = () => {
      createForm.name = ''
      createForm.year = ''
      createForm.startTime = ''
      createForm.endTime = ''
      createDialogVisible.value = true
    }

    // 显示编辑批次对话框
    const showEditDialog = (row) => {
      editForm.id = row.id
      editForm.name = row.name
      editForm.year = row.year
      editForm.startTime = row.startTime
      editForm.endTime = row.endTime
      editForm.extendEndTime = ''
      editDialogVisible.value = true
    }

    // 提交创建批次
    const handleCreateSubmit = () => {
      if (!createForm.name || !createForm.year || !createForm.startTime || !createForm.endTime) {
        ElMessage.warning('请填写完整信息')
        return
      }

      // 模拟提交成功
      const newBatch = {
        id: batchList.value.length + 1,
        name: createForm.name,
        year: createForm.year,
        startTime: createForm.startTime,
        endTime: createForm.endTime,
        status: '运行中',
        photos: []
      }

      batchList.value.unshift(newBatch)
      createDialogVisible.value = false
      ElMessage.success('创建批次成功')
    }

    // 提交编辑批次
    const handleEditSubmit = () => {
      if (!editForm.name || !editForm.year || !editForm.startTime || !editForm.endTime) {
        ElMessage.warning('请填写完整信息')
        return
      }

      // 更新批次信息
      const index = batchList.value.findIndex(item => item.id === editForm.id)
      if (index !== -1) {
        batchList.value[index] = {
          ...batchList.value[index],
          name: editForm.name,
          year: editForm.year,
          startTime: editForm.startTime,
          endTime: editForm.extendEndTime || editForm.endTime
        }
      }

      editDialogVisible.value = false
      ElMessage.success('编辑批次成功')
    }

    // 表格表头样式
    const headerCellStyle = () => {
      return {
        backgroundColor: '#f5f7fa',
        color: '#606266',
        fontWeight: '600'
      }
    }

    // 获取状态标签类型
    const getStatusType = (status) => {
      const statusMap = {
        '运行中': 'success',
        '已结束': 'info',
        '未开始': 'warning'
      }
      return statusMap[status] || ''
    }

    return {
      batchList,
      filteredBatchList,
      pagedBatchList,
      searchQuery,
      currentPage,
      pageSize,
      yearOptions,
      createDialogVisible,
      createForm,
      editDialogVisible,
      editForm,
      detailDialogVisible,
      currentDetail,
      goBack,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      showCreateDialog,
      showEditDialog,
      showDetailDialog,
      previewPhoto,
      handleCreateSubmit,
      handleEditSubmit,
      getStatusType,
      headerCellStyle
    }
  }
}
</script>

<style scoped lang="scss">
.activity-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  gap: 16px;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

  .title-container {
    .breadcrumb-title {
      display: flex;
      align-items: center;

      .main-title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
        position: relative;
        padding-left: 12px;

        &::before {
          content: "";
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 4px;
          height: 16px;
          background-color: #409EFF;
          border-radius: 2px;
        }
      }
    }
  }

  .header-actions {
    display: flex;
    gap: 12px;

    .back-btn, .create-btn {
      padding: 8px 15px;
      border-radius: 6px;

      .el-icon {
        margin-right: 5px;
      }
    }
  }
}

.search-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

  :deep(.el-card__body) {
    padding: 16px 20px;
  }

  .search-bar {
    display: flex;
    gap: 12px;

    .search-input {
      flex: 1;

      :deep(.el-input__inner) {
        padding-left: 32px;
      }

      :deep(.el-input__prefix) {
        display: flex;
        align-items: center;
        padding-left: 8px;
      }
    }

    .search-btn, .reset-btn {
      padding: 8px 15px;

      .el-icon {
        margin-right: 5px;
      }
    }
  }
}

.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  border: none;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

  :deep(.el-card__body) {
    padding: 0;
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .batch-table {
    flex: 1;

    :deep(.el-table__body-wrapper) {
      .el-table__body {
        tr:hover > td {
          background-color: #f5f7fa !important;
        }
      }
    }

    .status-tag {
      font-weight: 500;
    }

    .edit-btn, .detail-btn {
      padding: 5px 10px;

      .el-icon {
        margin-right: 5px;
      }
    }
  }

  .pagination {
    padding: 16px;
    border-top: 1px solid #ebeef5;
  }
}

.create-dialog, .edit-dialog, .detail-dialog {
  border-radius: 8px;

  :deep(.el-dialog__header) {
    padding: 16px 20px;
    border-bottom: 1px solid #ebeef5;
    margin-right: 0;

    .el-dialog__title {
      font-weight: 600;
      color: #303133;
    }
  }

  :deep(.el-dialog__body) {
    padding: 20px;
  }

  :deep(.el-dialog__footer) {
    padding: 16px 20px;
    border-top: 1px solid #ebeef5;
  }

  .dialog-form {
    :deep(.el-form-item__label) {
      font-weight: 500;
    }
  }

  .cancel-btn, .submit-btn, .close-btn {
    padding: 8px 20px;
    border-radius: 6px;
  }
}

.detail-content {
  padding: 0 20px;

  .detail-header {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 20px;

    h3 {
      margin: 0;
      font-size: 18px;
      color: #303133;
    }
  }

  .detail-info {
    margin-bottom: 24px;

    :deep(.el-descriptions__label) {
      font-weight: 500;
      width: 100px;
    }
  }

  .photo-section {
    .section-title {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 16px;
      font-size: 16px;
      font-weight: 500;
      color: #303133;

      .el-icon {
        color: #409EFF;
      }
    }

    .photo-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
      gap: 16px;

      .photo-item {
        border-radius: 6px;
        overflow: hidden;

        .photo-wrapper {
          position: relative;
          width: 100%;
          height: 160px;
          border-radius: 6px;
          overflow: hidden;

          .photo-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s;

            &:hover {
              transform: scale(1.05);
            }
          }

          .photo-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.3);
            opacity: 0;
            transition: opacity 0.3s;
            display: flex;
            align-items: flex-end;
            justify-content: flex-end;
            padding: 10px;

            .preview-btn {
              opacity: 0.8;
              transition: all 0.3s;

              &:hover {
                opacity: 1;
                transform: scale(1.1);
              }
            }
          }

          &:hover .photo-overlay {
            opacity: 1;
          }
        }

        .photo-desc {
          margin-top: 8px;
          font-size: 14px;
          color: #606266;
          text-align: center;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }

    .no-photos {
      padding: 40px 0;

      :deep(.el-empty__description) {
        margin-top: 10px;
        color: #909399;
      }
    }
  }
}

@media (max-width: 768px) {
  .header-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;

    .header-actions {
      width: 100%;

      .back-btn, .create-btn {
        width: 100%;
      }
    }
  }

  .search-bar {
    flex-direction: column;

    .search-input {
      width: 100%;
    }

    .search-btn, .reset-btn {
      width: 100%;
    }
  }

  .detail-dialog {
    width: 90% !important;
  }
}
</style>